package com.minshenglife.zanzan.web.weixin;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.minshenglife.commons.dal.Page;
import com.minshenglife.commons.security.utils.AccessTokenUtils;
import com.minshenglife.commons.security.utils.pp.UserIdentify;
import com.minshenglife.commons.security.utils.pp.UserIdentify.UserType;
import com.minshenglife.zanzan.entity.EndPlate;
import com.minshenglife.zanzan.entity.MailBox;
import com.minshenglife.zanzan.entity.RedFlower;
import com.minshenglife.zanzan.entity.User;
import com.minshenglife.zanzan.pub.Keys;
import com.minshenglife.zanzan.pub.message.MessageUtil;
import com.minshenglife.zanzan.pub.message.WXRespMessage;
import com.minshenglife.zanzan.pub.message.custservice.CS_TextMessage;
import com.minshenglife.zanzan.pub.utils.Message;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.result.EndPlateResult;
import com.minshenglife.zanzan.result.RuleHelp;
import com.minshenglife.zanzan.service.AccessTokenService;
import com.minshenglife.zanzan.service.EndPlateService;
import com.minshenglife.zanzan.service.MailBoxService;
import com.minshenglife.zanzan.service.RedFlowerService;
import com.minshenglife.zanzan.service.ReviewService;
import com.minshenglife.zanzan.service.RuleService;
import com.minshenglife.zanzan.service.UserService;
import com.minshenglife.zanzan.web.weixin.form.BindForm;
import com.minshenglife.zanzan.web.weixin.form.CommonDataForm;
import com.minshenglife.zanzan.web.weixin.form.StatForm;
import com.minshenglife.zanzan.web.weixin.model.WXUserInfo;
import com.minshenglife.zanzan.web.weixin.result.UserResult;
import com.minshenglife.zanzan.web.weixin.service.WXAccTokenService;
import com.minshenglife.zanzan.web.weixin.service.WXBaseService;
import com.nationsky.pub.utils.StringUtils;


/**
 * 微信赞赞
 * @author huodd
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	Logger log = LoggerFactory.getLogger(UserController.class);
	@Resource
	ReviewService reviewService;
	@Resource
	UserService userService;
	@Resource
	MailBoxService mailBoxService;
	@Resource
	EndPlateService endPlateService;
	@Resource
	RedFlowerService redFlowerService;
	@Resource
	AccessTokenService accessTokenService;
	@Resource
	WXAccTokenService tokenService;
	@Resource
	RuleService ruleService;
    
    @RequestMapping("/gotoRegister.do")
    public String list(HttpServletRequest request, HttpServletResponse response){
    	log.debug("start bindEmpNo method ");
    	String page="jsp/weixin/registerSuccess";
    	String openId=request.getParameter("openId");
    	log.debug("openId : "+openId);
    	User user=userService.getUserByWXCode(openId);
    	if(user==null){
    		page="jsp/weixin/register";
    	}else{
    		
    	}
    	log.debug("end bindEmpNo method ");
        return page;
    }
    
    /**
     * 绑定员工号
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="/bindEmpNo.do",method=RequestMethod.POST)
    @ResponseBody
    public String bindEmpNo(HttpServletRequest request, HttpServletResponse response,
    		BindForm bindForm){
    	log.debug("start bindEmpNo method ");
    	Message message=null;
    	try {
    		String openId=super.getOpenId(request);
			log.debug("当前绑定人的openId："+openId);
    		//校验用户信息是否正确
    		message=checkBindInfo(bindForm);
    		
			if(message!=null && Message.STATE_200.equals(message.getState())){
				//校验该员工号是否已经绑定
				User user=userService.getUserInfo(bindForm.getEmpNo());
				if(StringUtils.isNullOrEmpty(user.getWXCode())){
					WXUserInfo userInfo=WXBaseService.getWXUserInfo(openId,tokenService.getWXAccToken());
					user.setWXCode(openId);
					log.debug("========="+userInfo.getHeadimgurl());
					user.setHeadImageUrl(userInfo.getHeadimgurl());
					userService.updateUserInfo(user);
					
					try {
						//推送客服消息，告知用户已经绑定成功
						String to_message=user.getEmp_name()+"您好，欢迎加入民生保险微家！";
						CS_TextMessage tm=new CS_TextMessage();
						tm.setTouser(user.getWXCode());
						tm.setMsgtype(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
						tm.setText(to_message);
						WXRespMessage respMessage=WXBaseService.sendCustServiceMessage(tm,tokenService.getWXAccToken());
						log.info("==========="+respMessage.getErrcode());
						System.out.println("==========="+respMessage.getErrcode());
						if("0".equals(respMessage.getErrcode())){
							log.info("客服消息发送成功");
						}else{
							log.info("客服消息发送失败，错误信息："+respMessage.getErrmsg());
						}
					} catch (Exception e) {
						log.info("客服消息发送失败");
						e.printStackTrace();
					}
					
					//创建用户访问token，建立访问失效
					String access_token=AccessTokenUtils.newToken(new UserIdentify(UserType.weixin,openId), user.getIdNo());
					accessTokenService.insertAccessToken(user,access_token);//插入页面时效
					message=new Message(Message.STATE_200,access_token);
				}else{
					log.debug("{"+bindForm.getEmpNo()+"}该员工号已经绑定");
					message=new Message(Message.STATE_one,"亲，该员工号已被绑定，请使用自己的工号，如有疑问请联系系统管理员！");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
		}
    	log.debug("end bindEmpNo method ; return message : "+message);
        return message.toString();
    }
    /**
     * 绑定员工号
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="/empUnbound.do")
    @ResponseBody
    public void empUnbound(HttpServletRequest request, HttpServletResponse response){
    	log.debug("start empUnbound method ");
    	try {
    		String empId=super.getEmpId(request);
			log.debug("当前绑定人的empId："+empId);
    		//解除绑定
			userService.EmpUnbound(empId);
			//跳转至解绑成功页面
			log.debug(WXKeys.WX_BASEURL+"/jsp/success/success.jsp");
			response.sendRedirect(WXKeys.WX_BASEURL+"/jsp/success/success.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			try {
				response.sendRedirect(WXKeys.WX_BASEURL+"/jsp/error/error.jsp");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
    	log.debug("end empUnbound method ");
    }
    
    /**
     * 红花排行榜
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="/redFlowerRank.do",method=RequestMethod.POST)
    @ResponseBody
    public Message redFlowerRank(HttpServletRequest request, HttpServletResponse response,
    		StatForm statForm){
    	log.debug("=======start redFlowerRank()=======");
    	
    	Message message=null;
    	Page<User> page;
		try {
			int pageNo=statForm.getPageNo()==0? 1: statForm.getPageNo();
			int pageSize=statForm.getPageSize()==0? 10: statForm.getPageSize();
			Map<String,Object> map=new HashMap<String,Object>();
			page = userService.findFlowerRankList(map, pageNo, pageSize);
			message=new Message(Message.STATE_200,"",page);
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
			log.debug(message.toString());
		}
//    	log.debug(message.toString());
    	 return message;
    }
    /**
     * 送花排行榜
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="/sendFlowerRank.do",method=RequestMethod.POST)
    @ResponseBody
    public Message sendFlowerRank(HttpServletRequest request, HttpServletResponse response, StatForm statForm){
    	Message message=null;
    	Page<User> page;
		try {
			int pageNo=statForm.getPageNo()==0? 1: statForm.getPageNo();
			int pageSize=statForm.getPageSize()==0? 10: statForm.getPageSize();
			Map<String,Object> map=new HashMap<String,Object>();
			page = userService.findSendFlowerRankList(map, pageNo, pageSize); //送花
			message=new Message(Message.STATE_200,"",page);
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
			log.debug(message.toString());
		}
//    	log.debug(message.toString());
    	 return message;
    }
    /**
     * 进步排行榜
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="/progressRank.do",method=RequestMethod.POST)
    @ResponseBody
    public Message progressFlowerRank(HttpServletRequest request, HttpServletResponse response, StatForm statForm){
    	Message message=null;
    	Page<com.minshenglife.zanzan.result.UserResult> page;
		try {
			int pageNo=statForm.getPageNo()==0? 1: statForm.getPageNo();
			int pageSize=statForm.getPageSize()==0? 10: statForm.getPageSize();
			String operator=super.getEmpId(request);
			log.debug("当前操作人："+operator);
			Map<String,Object> map=new HashMap<String,Object>();
//			map.put("empId", operator);
			page = redFlowerService.findProgressRank(map, pageNo, pageSize); //进步榜
			message=new Message(Message.STATE_200,"",page);
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
			log.debug(message.toString());
		}
//    	log.debug(message.toString());
    	 return message;
    }
    /**
     * 积分排行榜
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="/integralRank",method=RequestMethod.POST)
    @ResponseBody
    public Message integralRank(HttpServletRequest request, HttpServletResponse response, StatForm statForm){
    	Message message=null;
    	Page<User> page;
		try {
			int pageNo=statForm.getPageNo()==0? 1: statForm.getPageNo();
			int pageSize=statForm.getPageSize()==0? 10: statForm.getPageSize();
			Map<String,Object> map=new HashMap<String,Object>();
			page = userService.findIntegralRankList(map, pageNo, pageSize); //积分
			message=new Message(Message.STATE_200,"",page);
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
			log.debug(message.toString());
		}
//    	log.debug(message.toString());
    	 return message;
    }
    /**
     * 校验用户信息是否正确
     * @param bindForm
     * @return
     */
    private Message checkBindInfo(BindForm bindForm) {
    	Message message=new Message(Message.STATE_200);
    	if(bindForm==null || StringUtils.isNullOrEmpty(bindForm.getEmpNo()) || StringUtils.isNullOrEmpty(bindForm.getIdNo()) ){
    		System.out.println();
    		message=new Message(Message.STATE_one,"信息有误请确认");
    	}else{
	    	boolean con=userService.isUser(bindForm.getEmpNo(), bindForm.getIdNo());
	    	if(!con){
	    		message=new Message(Message.STATE_one,"该员工不存在");
	    	}
    	}
		return message;
	}

    /**
     * 
    * 意见反馈
    * @param @param sdf    
    * @return void   
    * @throws
     */
    @RequestMapping(value="/mailBox.do",method=RequestMethod.POST)
    @ResponseBody
	public Message userAdivse(HttpServletRequest request, HttpServletResponse response, CommonDataForm commonDataForm){
    	Message message=null;
    	MailBox mailBox=new MailBox();
    	
    	try {
			String operator=super.getEmpId(request);
			log.debug("当前操作人："+operator);
			
			mailBox.setSendMailManId(operator); //发件人id
			mailBox.setAddresseeMainId(Keys.SYSTEM_SUPER_USER);//收件人id
			mailBox.setMailboxState(Keys.MAILSTATE_STATE_YFS);//已发送
			String content=commonDataForm.getData()!=null?commonDataForm.getData():"";
			if(content.length()<5){
				message=new Message(Message.STATE_one,"内容必须大于5个字符，谢谢");
			}else if(content.length()>50){
				message=new Message(Message.STATE_one,"内容超过50个字符，谢谢");
			}
			mailBox.setMailInfo(content);//内容
			mailBox.setCreate_time(new Date());
			mailBox.setUpdate_time(new Date());
			mailBoxService.insertUserAdv(mailBox);
			message=new Message(Message.STATE_200,"");
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"操作失败,服务器异常");
		}
    	return message;
    }
    
    /**
     * 吐槽列表
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="/endPlateList.do",method=RequestMethod.POST)
    @ResponseBody
    public Message endPlateList(HttpServletRequest request, HttpServletResponse response,
    		StatForm statForm){
    	Message message=null;
    	Page<EndPlateResult> page;
		try {
			int pageNo=statForm.getPageNo()==0? 1: statForm.getPageNo();
			int pageSize=statForm.getPageSize()==0? 10: statForm.getPageSize();
			Map<String,Object> map=new HashMap<String,Object>();
			page = endPlateService.findEndPlateInfo(map, pageNo, pageSize);
			message=new Message(Message.STATE_200,"",page);
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
			log.debug(message.toString());
		}
    	 return message;
    }
    
    /**
     * 吐槽提交
     * 吐槽现在的模式只有：不限制吐槽、用户抽奖吐槽、（每天奖励可吐槽数量为零）
     * @param request
     * @param response
     * @param bindForm
     * @return
     */
    @RequestMapping(value="/endPlate.do",method=RequestMethod.POST)
    @ResponseBody
    public Message endPlate(HttpServletRequest request, HttpServletResponse response,
    		CommonDataForm commonDataForm){
    	Message message=null;
    	try {
			String operator=super.getEmpId(request);
			log.debug("当前操作人："+operator);
			
			//获取规则中，可吐槽数量
			Long canTucaoNum=ruleService.getCanTucaoNumByRule(new Long(0));
			
			//canTucaoNum=-1 ;标识无限制
			if(canTucaoNum==-1){
				message = checkAndToEndPlace(commonDataForm, operator,
						canTucaoNum);
			}else{
				User user=userService.getUserInfo(operator);
				canTucaoNum=+user.getCanTuCaoNum();
				
				if(canTucaoNum==null || canTucaoNum==0){
					log.debug("抱歉，吐槽次数已用完");
					message=new Message(Message.STATE_one,"抱歉，吐槽次数已用完！");
				}else{
					message = checkAndToEndPlace(commonDataForm, operator,
							canTucaoNum);
				}
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
		}
    	return message;
    }

	private Message checkAndToEndPlace(CommonDataForm commonDataForm,
			String operator, Long canTucaoNum) {
		Message message;
		String content=commonDataForm.getData()!=null?commonDataForm.getData():"";
		//默认匿名吐槽
		String type=StringUtils.isNullOrEmpty(commonDataForm.getType())? Keys.REVIEW_CRITICS_TYPE_ONE	: commonDataForm.getType();
		if(content.length()<5){
			message=new Message(Message.STATE_one,"内容必须大于5个字符，谢谢!");
		}else if(content.length()>140){
			message=new Message(Message.STATE_one,"内容不得超过140个字符，谢谢!");
		}else{
			EndPlate endPlate=new EndPlate();
			endPlate.setEmpId(operator); //用户id
			endPlate.setEndPlateCon(content);//吐槽内容
			endPlate.setType(type);
			endPlate.setState(Keys.ENDPALTE_STATE_NORMAL);//状态：0 正常，1 删除
			endPlate.setCreate_time(new Date());
			
			Boolean con=true;//是否需要更新用户吐槽数
			if(canTucaoNum==-1)
				con=false;
			endPlateService.insertUserEndPlate(endPlate,con);
			message=new Message(Message.STATE_200,"");
		}
		return message;
	}
    
    /**
     * 我的吐槽
     * @param request
     * @param response
     * @param statForm
     * @return
     */
    @RequestMapping(value="/myEndPlate.do",method=RequestMethod.POST)
    @ResponseBody
    public Message myEndPlate(HttpServletRequest request, HttpServletResponse response,
    		StatForm statForm){
    	Message message=null;
    	Page<EndPlateResult> page;
		try {
			String operator=super.getEmpId(request);
			log.debug("当前操作人："+operator);
			int pageNo=statForm.getPageNo()==0? 1: statForm.getPageNo();
			int pageSize=statForm.getPageSize()==0? 10: statForm.getPageSize();
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("empId", operator);
			page = endPlateService.findEndPlateInfo(map, pageNo, pageSize);
			message=new Message(Message.STATE_200,"",page);
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
			log.debug(message.toString());
		}
    	 return message;
    }
    
    /**
     * 个人信息接口
     * @param request
     * @param response
     * @param statForm
     * @return
     */
    @RequestMapping(value="/personInfo.do")
    @ResponseBody
    public Message myInfo(HttpServletRequest request, HttpServletResponse response,
    		StatForm statForm){
    	Message message=null;
    	try {
			String operator=super.getEmpId(request);
			log.debug("当前操作人："+operator);
			String empId=statForm.getEmpId();
			log.debug("被查看人："+empId);
			//当被查看的人为null时，查询当前操作人信息
			if(StringUtils.isNullOrEmpty(empId))
				empId=operator;
			User user=userService.getUserInfo(empId);
			UserResult ur=new UserResult();
			ur.setEmpName(user.getEmp_name());
			ur.setHeadImageUrl(user.getHeadImageUrl());
			ur.setDeptName(user.getDeptName());
			ur.setIntegralGrade(user.getIntegralGrade());
			ur.setRedFlowerNum(user.getRedFlowerNum());
			ur.setRedflowerState(user.getRedflowerState());
			ur.setFdFlowerNum(user.getFdFlowerNum());
			ur.setIntegralNum(user.getIntegralNum());
			ur.setSendFlowerNum(user.getSendFlowerNum());
			ur.setTelephone(user.getTelephone());
			ur.setWork_email(user.getWork_email());
			ur.setCanSendNum(user.getCanSendNum());
			ur.setInteGraPic(user.getIntegralGradePic());
			
			Long canTucaoNum=user.getCanTuCaoNum();
			canTucaoNum=ruleService.getCanTucaoNumByRule(canTucaoNum);
			//今天可吐槽数量
			ur.setCanTuCaoNum(canTucaoNum);
			
			//今天可赠送的红花数 包括（抽奖所得可赠送数+今天可赠送数）
			Integer canSendNum=0;
			RuleHelp rh=ruleService.getCanSendFlowerNumByRule(canSendNum);
			canSendNum=rh.getCanSendFlowerNum();
			if(canSendNum!=-1){
				boolean con=false;
				Date startDate=new Date();
	    		Date endDate=new Date();
	    		if(rh.getRuleStartTime()!=null && rh.getRuleEndTime()!=null){
	    			startDate=rh.getRuleStartTime();
	    			endDate=rh.getRuleEndTime();
	    			con=true;
	    		}else{
	    			//只有非活动的时候才可以用户抽奖得来的机会
	    			canSendNum+=Integer.valueOf(user.getCanSendNum().toString());
	    		}
				//今日红花状态 获取该用户今天送出红花数量
	    		List<RedFlower> list=redFlowerService.findMyRedFlowerList(empId,startDate,endDate,con);
				if(list!=null&& list.size()!=0){
					int tnum=canSendNum-list.size();
					canSendNum=tnum>0 ? tnum :0;
				}
			}
			ur.setCanSendNumOfToday(canSendNum);
			message=new Message(Message.STATE_200,"",ur);
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
		}
    	
    	return message;
    }
    
    /**
     * 个人信息接口
     * @param request
     * @param response
     * @param statForm
     * @return
     */
    @RequestMapping(value="/searchEmpInfo.do")
    @ResponseBody
    public Message searchEmpInfo(HttpServletRequest request, HttpServletResponse response,
    		StatForm statForm){
    	Message message=null;
    	log.debug("beging searchEmpInfo()");
    	try {
			String operator=super.getEmpId(request);
			log.debug("当前操作人："+operator);
			List<com.minshenglife.zanzan.result.UserResult> list=null;
			if(StringUtils.isNullOrEmpty(statForm.getContent())){
				list=userService.initSearchEmpInfoList(operator);//搜索页面初始加载本部门信息
			}else{
				list=userService.findEmpInfoList(statForm.getContent());
			}
			
			message=new Message(Message.STATE_200,"",list);
		} catch (Exception e) {
			e.printStackTrace();
			message=new Message(Message.STATE_one,"服务器异常");
		}
    	
    	return message;
    }

    public static void main(String[] sdf){
		System.out.println("sadfd".substring(0, 1));
	}
   
}
